package com.hzw.code.utils

import android.net.ParseException
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import com.hzw.code.net.exception.Error
import com.hzw.code.net.exception.ResourceException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/4/18 9:57 PM
 *
 * @Description:    异常统一转换
 *
 */

fun convertException(e: Throwable): ResourceException = when(e){

    is ResourceException -> e //内部有使用, 避免都变成未知错误

    is HttpException -> ResourceException(Error.HTTP_ERROR, e)

    is JsonParseException -> ResourceException(Error.PARSE_ERROR, e)

    is JSONException -> ResourceException(Error.PARSE_ERROR, e)

    is ParseException -> ResourceException(Error.PARSE_ERROR, e)

    is MalformedJsonException -> ResourceException(Error.PARSE_ERROR, e)

    is ConnectException -> ResourceException(Error.NETWORD_ERROR, e)

    is SSLException -> ResourceException(Error.SSL_ERROR, e)

    is SocketTimeoutException -> ResourceException(Error.TIMEOUT_ERROR, e)

    is UnknownHostException -> ResourceException(Error.UNKNOWN_HOST_ERROR, e)

    else -> {
        if (e.message.isNullOrEmpty()) {
            ResourceException(Error.UNKNOWN,e)
        } else {
            ResourceException(Error.UNKNOWN.code, e.message!!,e)
        }
    }
}